﻿using Gameserver.Cache;
using Gameserver.DAO;
using Protocol.DTO;
using ServerFrame;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gameserver.Biz
{
    public class RoleBiz
    {
        RoleCache roleCache;
        UserCache userCache;
        public RoleBiz()
        {
            roleCache = CacheFactory.roleCache;
            userCache = CacheFactory.userCache;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="name"></param>
        /// <returns>
        /// 0 注册成功
        /// 1 该用户不在线
        /// 2 该用户对应账号不存在
        /// 3 该用户已有角色
        /// 4 该角色名已被创建
        /// </returns>
        public int Create(Mytoken token,string name)
        {
            User_DAO user=userCache.GetUserByToken(token);
            if(!userCache.isOnline(token))
            {
                return 1;
            }
            if(user==null)
            {
                return 2;
            }
            if(roleCache.hasRole(user.Role_id))
            {
                return 3;
            }
            if(roleCache.hasRole(name))
            {
                return 4;
            }
            roleCache.Create(user, name);
            return 0;
        }
        /// <summary>
        /// 角色登陆事务
        /// </summary>
        /// <param name="token"></param>
        /// <returns>
        /// 0 登陆成功
        /// 1 客户端没有连接
        /// 2 该连接没有对应账号
        /// 3 该账号没有角色
        /// 4 该角色已上线
        /// </returns>
        public int RoleLogin(Mytoken token)
        {
            if(!userCache.isOnline(token))
            {
                return 1;
            }
            if(!userCache.hasUser(userCache.GetNameByToken(token)))
            {
                return 2;
            }
            User_DAO user = userCache.GetUserByToken(token);
            int rid = user.Role_id;
            if(!roleCache.hasRole(rid))
            {
                return 3;
            }
            //string rname = roleCache.GetNameByToken(token); 不能使用GetNameByToken()，因为该函数是获取在线的连接的名称，而此时并没有连接上该缓存
            string rname = roleCache.RidToName[rid];
            if(roleCache.isOnline(rname))
            {
                return 4;
            }
            roleCache.Online(rname, token);
            return 0;
        }
        public void ClientClose(Mytoken token)
        {
            if (!roleCache.Online_token.ContainsKey(token))
                return;
            string name = roleCache.GetNameByToken(token);
            roleCache.Offline(name, token);
        }
    }
}
